package com.tepth.busfix.main.repair;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.tepth.busfix.R;
import com.tepth.busfix.adapter.ExpandableItemAdapter;
import com.tepth.busfix.adapter.entity.Level0Item;
import com.tepth.busfix.adapter.entity.Level1Item;
import com.tepth.busfix.bean.reponse.BusInfo;
import com.tepth.busfix.bean.reponse.BusRepairHistory;
import com.tepth.busfix.bean.reponse.CommonBean;
import com.tepth.busfix.bean.reponse.ListContentsBean;
import com.tepth.busfix.bean.reponse.ListRemarkBean;
import com.tepth.busfix.bean.reponse.PartBean;
import com.tepth.busfix.bean.reponse.Person;
import com.tepth.busfix.bean.reponse.Repair;
import com.tepth.busfix.bean.reponse.Trouble;
import com.tepth.busfix.bean.reponse.TroubleContent;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.main.login.LoginActivity;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.view.RecyclerViewDecoration;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangyu on 2017/9/6.
 */

public class HistoryFragment extends Fragment implements HistoryContract.View {
    private static final String PARAMETER = "busInfo";

    public static HistoryFragment newInstance(BusInfo busInfo) {
        HistoryFragment fragment = new HistoryFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PARAMETER, busInfo);
        fragment.setArguments(bundle);
        return fragment;
    }

    private BusInfo mBusInfo;

    private HistoryPresenter mPresenter;

    private RecyclerView mRecyclerView;
    private ExpandableItemAdapter mAdapter;
    private ArrayList<MultiItemEntity> mDatas = new ArrayList<>();
    private DialogDelegate mDialogDelegate;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBusInfo = (BusInfo) bundle.getSerializable(PARAMETER);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_history, container, false);
        initView(rootView);
        return rootView;
    }

    private void initView(View rootView) {
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv);
        SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeLayout_type);
        refreshLayout.setEnabled(false);
        mRecyclerView.addItemDecoration(new RecyclerViewDecoration(getActivity(),
                RecyclerViewDecoration.VERTICAL_LIST));
        setPresenter();
        mAdapter = new ExpandableItemAdapter(mDatas);
        mAdapter.setEmptyView(R.layout.view_load_data, (ViewGroup) mRecyclerView.getParent());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter);
        mPresenter.getRepairHistory();
        mDialogDelegate = new SweetAlertDialogDelegate(getActivity());
    }

    private void setPresenter() {
        mPresenter = new HistoryPresenter();
        HistoryModel model = new HistoryModel();
        mPresenter.setVM(this, model);
    }

    @Override
    public void onDestroyView() {
        mPresenter.onDestroy();
        if (mDialogDelegate != null) {
            mDialogDelegate.clearDialog();
        }
        super.onDestroyView();
    }

    @Override
    public void onNetworkError(String msg) {
        mAdapter.setEmptyView(R.layout.view_net_error, (ViewGroup) mRecyclerView.getParent());
    }

    @Override
    public void onError(String msg) {
        mAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) mRecyclerView.getParent());
    }

    @Override
    public void onTokenInvalid(String msg) {
        if (mDialogDelegate != null) {
            mDialogDelegate.showWarningDialog(msg, "请重新登录", new DialogDelegate.OnDialogListener() {
                @Override
                public void onClick() {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("reload", "reload");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            });
        }
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(getActivity(), SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getCode() {
        return mBusInfo.getVehicleCode();
        // return "81695";
    }

    @Override
    public void showData(List<BusRepairHistory> list) {
        if (list != null && !list.isEmpty()) {
            ArrayList<MultiItemEntity> res = new ArrayList<>();
            for (BusRepairHistory b : list) {
                Level0Item level0 = new Level0Item(b.getActualStartTime(), b.getMaintenanceTypeName());
                if (b.getType() == 2 || b.getType() == 1) {
                    //小修
                    Repair repair = b.getRepair();
                    if (repair != null) {
                        ArrayList<Trouble> troubles = repair.getListTrouble();
                        if (troubles != null && !troubles.isEmpty()) {
                            for (Trouble t : troubles) {
                                String troubleDes = t.getName();
                                if (troubleDes != null && troubleDes.contains("自定义录入@@")) {
                                    troubleDes = troubleDes.replaceAll("自定义录入@@", "附加作业项");
                                }
                                String fixContent;
                                String personName = "";
                                List<TroubleContent> contents = t.getListContent();
                                if (contents != null && !contents.isEmpty()) {
                                    for (TroubleContent content : contents) {
                                        fixContent = assemblyData(content);
                                        Person person = content.getWorkPerson();
                                        if (person != null) {
                                            personName = person.getName();
                                        }
                                        Level1Item level1 = new Level1Item(troubleDes, fixContent, personName);
                                        level0.addSubItem(level1);
                                    }

                                }

                            }
                        }
                    }
                } else {
                    //保养
                    List<ListContentsBean> contents = b.getListWorkContents();
                    if (contents != null && !contents.isEmpty()) {
                        for (ListContentsBean content : contents) {
                            List<ListRemarkBean> remarks = content.getListRemark();
                            if (remarks != null && !remarks.isEmpty()) {
                                for (ListRemarkBean listRemarkBean : remarks) {
                                    String troubleDes = listRemarkBean.getName();
                                    if (troubleDes != null && troubleDes.contains("@@")) {
                                        troubleDes = troubleDes.replaceAll("@@", "");
                                    }
                                    String fixContent = assemblyData(listRemarkBean);
                                    String personName = "";
                                    List<Person> persons = listRemarkBean.getListWorkPerson();
                                    if (persons != null && !persons.isEmpty()) {
                                        for (Person person : persons) {
                                            personName += person.getName() + "  ";
                                        }
                                    }
                                    Level1Item level1 = new Level1Item(troubleDes, fixContent, personName);
                                    level0.addSubItem(level1);
                                }
                            }
                        }
                    }
                }
                res.add(level0);
            }

            mDatas.addAll(res);
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) mRecyclerView.getParent());
        }

    }


    private String assemblyData(TroubleContent bean) {
        String operationContent = "";
        TroubleContent.Operation operationBean =
                bean.getOperation();
        if (operationBean != null) {
            operationContent += operationBean.getName();
        }
        TroubleContent.Part accessoryBean =
                bean.getAccessory();
        TroubleContent.Part componentBean =
                bean.getComponent();
        if (accessoryBean != null) {
            operationContent += accessoryBean.getName();
            operationContent += bean.getUseCount();
            operationContent += accessoryBean.getUnit();
        } else {
            if (componentBean != null) {
                operationContent += componentBean.getName();
                operationContent += bean.getUseCount();
                operationContent += componentBean.getUnit();
            }
        }
        return operationContent;
    }

    private String assemblyData(ListRemarkBean bean) {
        String operationContent = "";
        CommonBean operationBean =
                bean.getOperation();
        if (operationBean != null) {
            operationContent += operationBean.getName();
        }
        PartBean accessoryBean =
                bean.getAccessory();
        PartBean componentBean =
                bean.getComponent();
        if (accessoryBean != null) {
            operationContent += accessoryBean.getName();
            operationContent += bean.getUseCount();
            operationContent += accessoryBean.getUnit();
        } else {
            if (componentBean != null) {
                operationContent += componentBean.getName();
                operationContent += bean.getUseCount();
                operationContent += componentBean.getUnit();
            }
        }
        return operationContent;
    }
}
